import 'package:flutter/material.dart';

class FloatingScrollbarList extends StatefulWidget {
  const FloatingScrollbarList({super.key});

  @override
  _FloatingScrollbarListState createState() => _FloatingScrollbarListState();
}

class _FloatingScrollbarListState extends State<FloatingScrollbarList> {
  final ScrollController _scrollController = ScrollController();
  double _scrollBarPosition = 0.0;
  final double _scrollBarHeight = 80.0; // 滚动条的高度

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_updateScrollBar);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_updateScrollBar);
    _scrollController.dispose();
    super.dispose();
  }

  void _updateScrollBar() {
    if (!_scrollController.hasClients) return;
    double maxScrollExtent = _scrollController.position.maxScrollExtent;
    double offset = _scrollController.offset;
    double screenHeight = MediaQuery.of(context).size.height;

    // 计算滚动条的位置（映射到屏幕高度）
    // double newPosition =
    //     (offset / maxScrollExtent) * (screenHeight - _scrollBarHeight - 40);
    double newPosition =
        (offset / maxScrollExtent) * (screenHeight - _scrollBarHeight);
    newPosition = newPosition.clamp(0, screenHeight - _scrollBarHeight - 180);

    // double appBarHeight = kToolbarHeight; // AppBar默认高度 56
    // double statusBarHeight = 0;
    // //MediaQuery.of(context).padding.top; // 状态栏高度
    // double bottomPadding = 0;
    // //MediaQuery.of(context).padding.bottom; // 底部安全区域
    // double extraPadding = 0; // 额外调整值

    // double maxScrollBarPosition = screenHeight -
    //     _scrollBarHeight -
    //     (appBarHeight + statusBarHeight + bottomPadding + extraPadding);

    // newPosition = newPosition.clamp(0, maxScrollBarPosition);

    setState(() {
      _scrollBarPosition = newPosition;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("悬浮滚动条示例")),
      body: Stack(
        children: [
          ListView.builder(
            controller: _scrollController,
            itemCount: 50,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text("Item $index"),
              );
            },
          ),
          Positioned(
            right: 10,
            top: _scrollBarPosition + 20, // 偏移一点避免贴顶
            child: Container(
              height: _scrollBarHeight,
              width: 8,
              decoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.7),
                borderRadius: BorderRadius.circular(4),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
